package org.daoImpl;

import org.dao.WikiDao;
import org.model.Wiki;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;

import java.util.List;

/**
 * Created by tedzy on 2015/5/18.
 * Wiki Dao Impl
 */
public class WikiDaoImpl extends HibernateDaoSupport implements WikiDao {
    @Override
    public int newWiki(String title, String content) {
        Wiki wiki = new Wiki();
        wiki.setTitle(title);
        wiki.setContent(content);
        this.getHibernateTemplate().save(wiki);
        return wiki.getId();
    }

    @Override
    public boolean editWiki(int id, String title, String content) {
        List list = this.getHibernateTemplate().find("from Wiki where id=?", id);
        if (list.size() <= 0) {
            return false;
        }
        Wiki wiki = (Wiki) list.get(0);
        wiki.setTitle(title);
        wiki.setContent(content);
        this.getHibernateTemplate().update(wiki);
        return true;
    }

    @Override
    public Wiki getWiki(String title) {
        Wiki wiki = null;
        List list = this.getHibernateTemplate().find("from Wiki where title=?", title);
        if (list.size() > 0) {
            wiki = (Wiki) list.get(0);
        }
        return wiki;
    }

    @Override
    public Wiki getWikiById(int wikiid) {
        Wiki wiki = null;
        List list = this.getHibernateTemplate().find("from Wiki where id=?", wikiid);
        if(list.size()>0){
            wiki = (Wiki) list.get(0);
        }
        return wiki;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Wiki> searchWiki(String title) {
        return (List<Wiki>) this.getHibernateTemplate().find("from Wiki where title like '%" + title + "%'");
    }
}
